package cn.dogeye.filters;

import cn.dogeye.service.impl.MyUserDetailServiceImpl;
import cn.dogeye.util.JwtUtil;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

	@Autowired
	JwtUtil jwtUtil;

	@Autowired
	MyUserDetailServiceImpl userDetailService;

	public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
		super(authenticationManager);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

		try {
			String jwt = request.getHeader(jwtUtil.getHeader());
			if (StrUtil.isBlankOrUndefined(jwt)) {
				chain.doFilter(request, response);
				return;
			}

			Claims claim = jwtUtil.getClaimByToken(jwt);
			if (claim == null) {
				throw new JwtException("token 异常");
			}

			String sno = claim.getSubject();
			// 获取用户的权限等信息
			String auths = claim.get("authority").toString();
			UsernamePasswordAuthenticationToken token
					= new UsernamePasswordAuthenticationToken(sno, null, AuthorityUtils.commaSeparatedStringToAuthorityList(auths));
			SecurityContextHolder.getContext().setAuthentication(token);
			chain.doFilter(request, response);

		}catch (ExpiredJwtException e){
			throw new JwtException("token已过期");
		}catch (Exception e){
			throw new RuntimeException(e.getMessage());
		}

	}
}
